package com.hr.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
 * 校验码控制类
 * @author fazhen.zheng
 *
 */
@Controller
public class VerifyController {
	@RequestMapping("/getImage")
	public void verifyImage(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		HttpSession session = request.getSession(true);
		response.setContentType("text/html; charset=UTF-8");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0L);
		response.setContentType("image/jpeg");
		int width = 60;
		int height = 20;
		BufferedImage image = null;
		Random random = null;
		Font font = null;
		try {
			image = new BufferedImage(width, height, 1);
			random = new Random();
			Graphics g = image.getGraphics();
			g.setColor(getRandColor(200, 250));
			g.fillRect(0, 0, width, height);
			font = new Font("宋体", 2, 18);
			g.setFont(font);
			g.drawRect(0, 0, width - 1, height - 1);
			g.setColor(getRandColor(160, 200));
			for (int i = 0; i < 155; i++) {
				int x = random.nextInt(width);
				int y = random.nextInt(height);
				int xl = random.nextInt(12);
				int yl = random.nextInt(12);
				g.drawLine(x, y, x + xl, y + yl);
			}

			String sRand = "";
			for (int i = 0; i < 4; i++) {
				String rand = String.valueOf(random.nextInt(10));
				sRand = sRand + rand;
				g.setColor(new Color(20 + random.nextInt(110), 20 + random
						.nextInt(110), 20 + random.nextInt(110)));
				g.drawString(rand, i * 14 + 4, 17);
			}

			session.removeAttribute("valifyCode");
			session.setAttribute("valifyCode", sRand);

			g.dispose();
			ServletOutputStream sos = null;
			try {
				sos = response.getOutputStream();
				ImageIO.write(image, "jpeg", sos);
			} catch (Exception ex) {
				//ex.printStackTrace();
			} finally {
				if (sos != null) {
					sos.flush();
					sos.close();
				}
			}
		} finally {
			if (random != null) {
				random = null;
			}
			if (font != null) {
				font = null;
			}
			if (image != null) {
				image.flush();
				image = null;
			}
		}

	}

	private Color getRandColor(int fc, int bc) {
		Random random = new Random();
		if (fc > 255)
			fc = 255;
		if (bc > 255)
			bc = 255;
		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc - fc);
		int b = fc + random.nextInt(bc - fc);
		return new Color(r, g, b);
	}
}
